<template>
  <div class="user-coupon-container">
    <a-card title="用户优惠券管理">
      <!-- 搜索区域 -->
      <div class="search-wrapper">
        <a-form layout="inline" :model="searchForm">
          <div class="search-row">
            <a-form-item label="优惠券">
              <a-select
                v-model:value="searchForm.couponId"
                placeholder="请选择优惠券"
                style="width: 200px"
                allowClear
                show-search
                :filter-option="false"
                :options="couponOptions"
                :loading="couponLoading"
                @search="handleSearchCoupon"
              >
                <template #optionLabel="{ label, value }">
                  <div>
                    <div>{{ label }}</div>
                    <div style="font-size: 12px; color: rgba(0, 0, 0, 0.45)">ID: {{ value }}</div>
                  </div>
                </template>
              </a-select>
            </a-form-item>
            <a-form-item label="用户">
              <a-select
                v-model:value="searchForm.userId"
                placeholder="请选择用户"
                style="width: 200px"
                allowClear
                show-search
                :filter-option="false"
                :options="userOptions"
                :loading="userLoading"
                @search="handleSearchUser"
              >
                <template #optionLabel="{ label, value }">
                  <div>
                    <div>{{ label }}</div>
                    <div style="font-size: 12px; color: rgba(0, 0, 0, 0.45)">ID: {{ value }}</div>
                  </div>
                </template>
              </a-select>
            </a-form-item>
            <a-form-item label="状态">
              <a-select
                v-model:value="searchForm.status"
                placeholder="请选择状态"
                style="width: 160px"
                allowClear
              >
                <a-select-option :value="USER_COUPON_STATUS.UNUSED">{{ USER_COUPON_STATUS_TEXT[USER_COUPON_STATUS.UNUSED] }}</a-select-option>
                <a-select-option :value="USER_COUPON_STATUS.USED">{{ USER_COUPON_STATUS_TEXT[USER_COUPON_STATUS.USED] }}</a-select-option>
                <a-select-option :value="USER_COUPON_STATUS.EXPIRED">{{ USER_COUPON_STATUS_TEXT[USER_COUPON_STATUS.EXPIRED] }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item class="search-buttons">
              <a-space>
                <a-button type="primary" @click="handleSearch">搜索</a-button>
                <a-button @click="handleReset">重置</a-button>
              </a-space>
            </a-form-item>
          </div>
        </a-form>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="userCouponList"
        :loading="loading"
        :pagination="{
          ...pagination,
          showTotal: (total: number) => `总计 ${total} 条数据`
        }"
        @change="handleTableChange"
        rowKey="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userName'">
            <span>{{ record.user?.userName || '-' }}</span>
          </template>
          <template v-if="column.key === 'couponName'">
            <span>{{ record.coupon?.name || '-' }}</span>
          </template>
          <template v-if="column.key === 'couponType'">
            <a-tag :color="record.coupon?.type === COUPON_TYPE.PERCENT ? 'blue' : 'green'" v-if="record.coupon?.type">
              {{ COUPON_TYPE_TEXT[record.coupon?.type] || '未知类型' }}
            </a-tag>
            <span v-else>-</span>
          </template>
          <template v-if="column.key === 'discountAmount'">
            <span v-if="record.coupon?.type === COUPON_TYPE.PERCENT">{{ record.coupon?.discountAmount }}%</span>
            <span v-else-if="record.coupon?.discountAmount">¥{{ record.coupon?.discountAmount }}</span>
            <span v-else>-</span>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag 
              :color="getStatusColor(record.status)"
            >
              {{ USER_COUPON_STATUS_TEXT[record.status] || '未知状态' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'validPeriod'">
            {{ formatDate(record.coupon?.startTime) }} 至 {{ formatDate(record.coupon?.endTime) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleStatusChange(record, USER_COUPON_STATUS.UNUSED)" v-if="record.status !== USER_COUPON_STATUS.UNUSED">标为未使用</a-button>
              <a-button type="link" @click="handleStatusChange(record, USER_COUPON_STATUS.USED)" v-if="record.status !== USER_COUPON_STATUS.USED">标为已使用</a-button>
              <a-button type="link" @click="handleStatusChange(record, USER_COUPON_STATUS.EXPIRED)" v-if="record.status !== USER_COUPON_STATUS.EXPIRED">标为已过期</a-button>
              <a-popconfirm
                title="确定要删除这个用户优惠券吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { 
  listUserCouponByPageUsingPost,
  updateUserCouponUsingPost,
  deleteUserCouponUsingPost
} from '@/api/userCouponController'
import { listCouponVoByPageUsingPost } from '@/api/couponController'
import { listUserVoByPageUsingPost } from '@/api/userController'
import { COUPON_TYPE, COUPON_TYPE_TEXT, USER_COUPON_STATUS, USER_COUPON_STATUS_TEXT } from '@/constants/coupon'

// 搜索表单
const searchForm = ref({
  couponId: undefined,
  userId: undefined,
  status: undefined,
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend'
})

// 优惠券下拉选项
const couponOptions = ref<{label: string, value: number}[]>([])
const couponLoading = ref(false)

// 用户下拉选项
const userOptions = ref<{label: string, value: number}[]>([])
const userLoading = ref(false)

// 表格数据
const loading = ref<boolean>(false)
const userCouponList = ref<any[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格列定义
const columns = [
  {
    title: '关联ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '用户名',
    key: 'userName',
    width: 120
  },
  {
    title: '优惠券名称',
    key: 'couponName',
    width: 150
  },
  {
    title: '优惠券类型',
    key: 'couponType',
    width: 100
  },
  {
    title: '优惠金额',
    key: 'discountAmount',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '有效期',
    key: 'validPeriod',
    width: 200
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 170,
    sorter: true
  },
  {
    title: '操作',
    key: 'action',
    width: 220
  }
]

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    [USER_COUPON_STATUS.UNUSED]: 'green',
    [USER_COUPON_STATUS.USED]: 'blue',
    [USER_COUPON_STATUS.EXPIRED]: 'gray'
  }
  return colorMap[status] || 'default'
}

// 格式化日期
const formatDate = (date?: string) => {
  if (!date) return '--'
  return dayjs(date).format('YYYY-MM-DD')
}

// 处理优惠券搜索
const handleSearchCoupon = async (searchValue: string) => {
  if (!searchValue) {
    couponOptions.value = []
    return
  }
  
  couponLoading.value = true
  try {
    const res = await listCouponVoByPageUsingPost({
      name: searchValue,
      current: 1,
      pageSize: 10
    })
    
    if (res.data?.records) {
      couponOptions.value = res.data.records.map(item => ({
        label: item.name || '未命名优惠券',
        value: item.id
      }))
    }
  } catch (error) {
    console.error('搜索优惠券出错:', error)
  } finally {
    couponLoading.value = false
  }
}

// 处理用户搜索
const handleSearchUser = async (searchValue: string) => {
  if (!searchValue) {
    userOptions.value = []
    return
  }
  
  userLoading.value = true
  try {
    const res = await listUserVoByPageUsingPost({
      userName: searchValue,
      current: 1,
      pageSize: 10
    })
    
    if (res.data?.records) {
      userOptions.value = res.data.records.map(item => ({
        label: item.userName || '未命名用户',
        value: item.id
      }))
    }
  } catch (error) {
    console.error('搜索用户出错:', error)
  } finally {
    userLoading.value = false
  }
}

// 获取用户优惠券列表
const fetchUserCouponList = async () => {
  loading.value = true
  try {
    const response = await listUserCouponByPageUsingPost({
      ...searchForm.value
    })
    if (response.data) {
      userCouponList.value = response.data.records || []
      pagination.total = response.data.total || 0
      pagination.current = response.data.current || 1
      pagination.pageSize = response.data.size || 10  
    } else {
      message.error('获取用户优惠券列表失败')
    }
  } catch (error: any) {
    message.error('获取用户优惠券列表出错')
    console.error('获取用户优惠券列表出错:', error)
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  searchForm.value.current = pag.current
  searchForm.value.pageSize = pag.pageSize
  
  if (sorter.field) {
    searchForm.value.sortField = sorter.field
    searchForm.value.sortOrder = sorter.order === 'ascend' ? 'asc' : 'desc'
  }
  
  fetchUserCouponList()
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  searchForm.value.current = 1
  fetchUserCouponList()
}

// 重置处理
const handleReset = () => {
  searchForm.value.couponId = undefined
  searchForm.value.userId = undefined
  searchForm.value.status = undefined
  pagination.current = 1
  searchForm.value.current = 1
  fetchUserCouponList()
}

// 更改状态
const handleStatusChange = async (record: any, newStatus: string) => {
  try {
    const response = await updateUserCouponUsingPost({
      id: record.id,
      status: newStatus
    })
    if (response.data) {
      message.success(`状态已更改为${USER_COUPON_STATUS_TEXT[newStatus]}`)
      fetchUserCouponList()
    } else {
      message.error('更改状态失败')
    }
  } catch (error: any) {
    message.error('更改状态出错')
    console.error('更改状态出错:', error)
  }
}

// 删除用户优惠券
const handleDelete = async (record: any) => {
  try {
    const response = await deleteUserCouponUsingPost({ id: record.id })
    if (response.data) {
      message.success('删除用户优惠券成功')
      fetchUserCouponList()
    } else {
      message.error('删除用户优惠券失败')
    }
  } catch (error: any) {
    message.error('删除用户优惠券出错')
    console.error('删除用户优惠券出错:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUserCouponList()
})
</script>

<style scoped>
.user-coupon-container {
  padding: 10px 0;
}

.search-wrapper {
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.search-buttons {
  margin-left: auto;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f7f7f7;
}

:deep(.ant-tag) {
  margin-right: 0;
}

/* 下拉选择器样式优化 */
:deep(.ant-select-dropdown) {
  max-width: 400px;
}

:deep(.ant-select-item-option-content) {
  white-space: normal;
  word-break: break-all;
}
</style> 